﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZLCMS.Data.Model;
using ZLCMS.Business.DwzFrame;
using Newtonsoft.Json;
using ZLCMS.Business.TranferParam;
using ZLCMS.Business.Util;
using NHibernate;
using ZLCMS.Business;
using NHibernate.Criterion;
using DotNet.Common.TransferParam;

namespace ZLCMS.Web.SystemManage.Basics.Param
{
    public partial class Edit : System.Web.UI.Page
    {
        public class ItemExpData
        {
            public bool Enable;

            public string GroupCode;

            public string GroupName;

            public string Relation;

            public ItemExpData()
            {
                Enable = false;
                Relation = null;
            }
        }

        public ItemExpData[] _itemExpDataList;

        protected FrameHelper _framePage;

        protected SysParam _paramItemDb, _paramGroupDb;

        protected List<ParamItemExp> _expItemList;

        protected List<ParamGroupExp> _expGroupList;

        private const int MaxExp = 5;

        protected void Page_Load(object sender, EventArgs e)
        {
            _framePage = new FrameHelper(this);

            InitContent();

            InitVariable();

            InitControlData();

            if (!IsPostBack)
            {
            }
            else if (IsPostBack)
            {
                SaveDoc();
            }
        }

        /// <summary>
        /// 初始化全局变量
        /// </summary>
        private void InitVariable()
        {
            int i;

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                try
                {
                    _paramItemDb = session.CreateCriteria<SysParam>().Add(Expression.Eq("GroupCode", item_id.Value)).Add(Expression.Eq("ItemCode", value_id.Value)).UniqueResult<SysParam>();
                    
                    _paramGroupDb = session.CreateCriteria<SysParam>().Add(Expression.Eq("GroupCode", group_id.Value)).Add(Expression.Eq("ItemCode", item_id.Value)).UniqueResult<SysParam>();
                }
                catch (System.Exception ex)
                {
                    _framePage.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _expItemList = JsonConvert.DeserializeObject<List<ParamItemExp>>(_paramItemDb.Param5 == null ? "" : _paramItemDb.Param5);
            _expGroupList = JsonConvert.DeserializeObject<List<ParamGroupExp>>(_paramGroupDb.Param5 == null ? "" : _paramGroupDb.Param5);

            _itemExpDataList = new ItemExpData[MaxExp];

            for (i = 0; i < MaxExp;i++ )
            {
                _itemExpDataList[i] = new ItemExpData();
            }

            if (_expGroupList != null)
            {
                i = 0;
                foreach (ParamGroupExp groupExp in _expGroupList)
                {
                    _itemExpDataList[i].Enable = true;
                    _itemExpDataList[i].GroupName = groupExp.Name;
                    _itemExpDataList[i].GroupCode = groupExp.Code;
                    _itemExpDataList[i].Relation = groupExp.Relation;
                    i++;
                }
            }
        }

        /// <summary>
        /// 初始化控件和控件的默认值
        /// </summary>
        private void InitControlData()
        {
            int i;

            if (!IsPostBack)
            {
                tb_code.Text = _paramItemDb.ItemCode;
                tb_value.Text = _paramItemDb.ItemValue;

                if (_expGroupList != null)
                {
                    i = 0;
                    foreach (ParamGroupExp groupExp in _expGroupList)
                    {
                        // 有关联参数，使用下拉框
                        if (!string.IsNullOrEmpty(groupExp.Relation.Trim()))
                        {
                            // 初始化下拉框的内容
                            Bindddl(i, groupExp.Relation);
                        }
                        i++;
                    }
                }

                //根据数据库中参数项扩展内容，对控件进行赋值
                for (i = 0; i < MaxExp; i++)
                {
                    if (!_itemExpDataList[i].Enable)
                    {
                        return;
                    }

                    if (_expItemList == null)
                    {
                        return;
                    }

                    foreach (ParamItemExp itemExp in _expItemList)
                    {
                        if (_itemExpDataList[i].GroupCode == itemExp.Code)
                        {
                            SetControlValue(i, itemExp.Value);
                            break;
                        }
                    }
                }
            }
        }

        private void SetControlValue(int index, string value)
        {
            switch (index)
            {
                case 0: { ddl_list_0.SelectedValue = value; tb_list_0.Text = value; break; }
                case 1: { ddl_list_1.SelectedValue = value; tb_list_1.Text = value; break; }
                case 2: { ddl_list_2.SelectedValue = value; tb_list_2.Text = value; break; }
                case 3: { ddl_list_3.SelectedValue = value; tb_list_3.Text = value; break; }
                case 4: { ddl_list_4.SelectedValue = value; tb_list_4.Text = value; break; }
            }
        }


        private string GetControlValue(int index)
        {
            if (!string.IsNullOrEmpty(_itemExpDataList[index].Relation.Trim()))
            {
                switch (index)
                {
                    case 0: return ddl_list_0.SelectedValue;
                    case 1: return ddl_list_1.SelectedValue;
                    case 2: return ddl_list_2.SelectedValue;
                    case 3: return ddl_list_3.SelectedValue;
                    case 4: return ddl_list_4.SelectedValue;
                }
            }
            else
            {
                switch (index)
                {
                    case 0: return tb_list_0.Text;
                    case 1: return tb_list_1.Text;
                    case 2: return tb_list_2.Text;
                    case 3: return tb_list_3.Text;
                    case 4: return tb_list_4.Text;
                }
            }
            return "";
        }

        private void Bindddl(int index, string group)
        {
            switch (index)
            {
                case 0: ParamKit.Bind(group, ddl_list_0, null, null, null, "-1", null);
                    break;
            }
        }

        private void InitContent()
        {
            if (!IsPostBack)
            {
                group_id.Value = Request["gid"];
                item_id.Value = Request["iid"];
                value_id.Value = Request["vid"];
            }
        }

        private void SaveDoc()
        {
            int i;

            _paramItemDb.ItemCode = tb_code.Text;
            _paramItemDb.ItemValue = tb_value.Text;

            List<ParamItemExp> itemExpList = new List<ParamItemExp>();

            for (i = 0; i < MaxExp; i++)
            {
                if (!_itemExpDataList[i].Enable)
                {
                    break;;
                }

                itemExpList.Add(new ParamItemExp(_itemExpDataList[i].GroupCode, GetControlValue(i)));

            }
            _paramItemDb.Param5 = JsonConvert.SerializeObject(itemExpList);

            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                session.Update(_paramItemDb);
                session.Flush();
            }

            _framePage.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _framePage.NavTabId,
                callbackType = "closeCurrent"
            });
        }
    }
}
